import 'dart:async';
import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:webview_flutter/webview_flutter.dart';

/// Created by XieXin on 2020/12/9.
/// WebView封装
class XWebView extends StatefulWidget {
  final String initialUrl;

  const XWebView(
    this.initialUrl, {
    Key? key,
  }) : super(key: key);

  @override
  XWebViewState createState() => XWebViewState();
}

class XWebViewState extends State<XWebView> {
  late WebViewController _controller;

  ///是否显示加载 true是
  bool _isShowProgress = false;

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
            LogUtil.v("XWebView onProgress : $progress");
          },
          onPageStarted: (String url) {
            //页面开始加载时调用
            LogUtil.v("XWebView onPageStarted : $url");
            _isShowProgress = true;
            setState(() {});
          },
          onPageFinished: (String url) {
            //页面加载完成时调用
            LogUtil.v("XWebView onPageFinished : $url");
            _isShowProgress = false;
            setState(() {});
          },
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.prevent;
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.initialUrl));
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        WebViewWidget(controller: _controller),
        _isShowProgress
            ? SpinKitThreeBounce(
                color: Theme.of(context).primaryColor,
              ) //动画控件根据自己需求改动
            : const SizedBox.shrink(),
      ],
    );
  }
}
